<form action="/admin/save" method="post" class="settings">
<? foreach($data as $k=>$setting): ?>
<? $functionName = 'setting_' . $setting['key'] ?>
    <? if (function_exists($functionName)): ?>
        <?= call_user_func($functionName, $k, $setting) ?>
    <? else: ?>
        <?= setting_item($k, $setting) ?>
    <? endif ?>
<? endforeach ?>

<br clear="all">
<input type="submit" value="Сачувај">
</form><?php

function setting_item($index, $setting, $type = 'text') {
    global $backgrounds;
    $id    = $setting['id'];
    $key   = $setting['key'];
    $value = $setting['value'];
    $label = $setting['label'];

    $html = '<p class="setting-item '.$type.'">'.
            '<label for="data'.$key.'">'.$label.'</label>'.
            '<input type="hidden" name="data['.$index.'][id]" value="'.$id.'">';
    
    switch($type) {

        case 'background':
            $html .= '<select onchange="updateBackgroundPreview()" name="data['.$index.'][value]"><option value="">---</option>';
            foreach (\Controller\App::bodyBackgrounds() as $background) {
                $selected = $value == $background ? ' selected="selected"' : '';
                $html .= '<option'.$selected.'>'.$background.'</option>';
            }
            $html .= '</select><br>'.
                     '<img src="/img/background/'.$value.'">';
            break;

        default:
            $html .= '<input type="text" name="data['.$index.'][value]" value="'.$value.'">';
            break;
    }
    
    return $html . '</p>';
}

function setting_kontakt_pozadina($index, $setting) {
    return setting_item($index, $setting, 'background');
}
?>
<script type="text/javascript">
$(function(){
    updateBackgroundPreview();
});
function updateBackgroundPreview() {
    var sel = $('select').first();
    var img = sel.nextAll('img').first();

    if (sel.val().length>0) {
        img
            .attr('src', '/img/background/'+sel.val())
            .show();
    } else {
        img.hide();
    }
}
</script>